import 'package:fish_redux/fish_redux.dart';
import 'dart:convert' as convert;
import 'action.dart';
import 'state.dart';
import '../model/order_view_model.dart';
import '../../../app_files.dart';

Reducer<OrderResultViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<OrderResultViewState>>{
      OrderResultViewAction.action: _onAction,
      OrderResultViewAction.onTapStatus: _onTapStatus,
      OrderResultViewAction.setOrderPhoto: _setOrderPhoto,
      OrderResultViewAction.setFixPhoto: _setFixPhoto,
      OrderResultViewAction.onGetData: _onGetData,
    },
  );
}

OrderResultViewState _onAction(OrderResultViewState state, Action action) {
  final OrderResultViewState newState = state.clone();
  return newState;
}

OrderResultViewState _onTapStatus(OrderResultViewState state, Action action) {
  final OrderResultViewState newState = state.clone()
    ..orderStatus = action.payload + 1;
  return newState;
}

OrderResultViewState _setOrderPhoto(OrderResultViewState state, Action action) {
  final OrderResultViewState newState = state.clone();
  newState.orderPhoto.add(action.payload);
  return newState;
}

OrderResultViewState _setFixPhoto(OrderResultViewState state, Action action) {
  final OrderResultViewState newState = state.clone();
  newState.repairPhotos.add(action.payload);
  return newState;
}

OrderResultViewState _onGetData(OrderResultViewState state, Action action) {
  final OrderResultViewState newState = state.clone();
  newState.orderStatus = int.tryParse(CommonUtils.checkNullToString(
          action.payload['scworkResultstatus'])) ??
      0;
  newState.orderSignPhoto = action.payload['scworkSignature'];
  String photos = action.payload['scworkAttachment'];
  newState.orderPhoto = photos.split(',');
  List list = convert.jsonDecode(action.payload['scworkContent']);
  List<OrderConfigModel> items =
      list.map<OrderConfigModel>((e) => OrderConfigModel.fromJson(e)).toList();
  newState.items = items;
  newState.workerName =
      CommonUtils.checkNullToString(action.payload['scworkInspectorname']);
  if (newState.orderStatus == 2) {
    String jsonContent = CommonUtils.checkNullToString(
        action.payload['scworkArepairAfterremark']);
    String fixPhotos = CommonUtils.checkNullToString(
        action.payload['scworkArepairAfterattachment']);
    print(jsonContent);
    Map info = convert.jsonDecode(jsonContent);
    newState.selfFixContentController.text = info['RepairContent'];
    if (fixPhotos.isNotEmpty) newState.repairPhotos = fixPhotos.split(',');
  }

  newState.gasInfo = UserGasInfo.fromJson(action.payload);

  return newState;
}
